package com.jeasonzhao.commons.inplacecache;

import java.util.Iterator;

public class CacheValuesIterator<V> implements Iterator<V>
{
    private Iterator<? extends CacheObject<?,V>> iterator;
    private CacheObject<?,V> nextValue;
    public CacheValuesIterator(AbstractCacheMap<?,V> abstractCacheMap)
    {
        iterator = null == abstractCacheMap || null == abstractCacheMap.getCacheMap() ?
            null
            : abstractCacheMap.getCacheMap().values().iterator();
        nextValue();
    }

    private void nextValue()
    {
        while(null != iterator && iterator.hasNext())
        {
            nextValue = iterator.next();
            if(nextValue.isExpired() == false)
            {
                return;
            }
        }
        nextValue = null;
    }

    public boolean hasNext()
    {
        return nextValue != null;
    }

    public V next()
    {
        V cachedObject = null == nextValue ? null : nextValue.getObject();
        nextValue();
        return cachedObject;
    }

    public void remove()
    {
        iterator.remove();
    }
}
